﻿using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Linq.Expressions;
using ToolMonitoring.WebApi.Dependency;
using ToolMonitoring.WebApi.Entities;
using ToolMonitoring.WebApi.Rep;

namespace ToolMonitoring.WebApi.Services
{
	public class AuditLogService:ISingletonDependency
	{
		private readonly AuditLogRepository _auditInfoRepository;
		private readonly ILogger<AuditLogService> _logger;
		
		public required ILogger Logger { get; init; }
		public AuditLogService(AuditLogRepository auditInfoRepository, ILogger<AuditLogService> logger)
		{
			_auditInfoRepository = auditInfoRepository;
			_logger = logger;
		}


		public async Task<AuditLog> Add(AuditLog data)
		{
			_auditInfoRepository.Insert(data);
			return await Task.FromResult(data);
		}

		public async Task<AuditLog> FindById(Guid id)
		{
			var result = _auditInfoRepository.FindById(id);
			return await Task.FromResult(result);
		}

		public async Task<List<AuditLog>> FindAll()
		{
			
			var result = _auditInfoRepository.FindAll().ToList();
			return await Task.FromResult(result);
		}

		public async Task<List<AuditLog>> Find(Expression<Func<AuditLog, bool>> expression)
		{
			var result = _auditInfoRepository.Find(expression).ToList();
			return await Task.FromResult(result);
		}

		public async Task<PageResult<AuditLog>> Find(AuditLog data,
			int pageIndex=1, int pageSize=10)
		{
			_logger.LogInformation("Find");
			Logger.LogInformation("FIND");

			var query = _auditInfoRepository.Collection.Query()
				.Where(c => c.MethodName.Contains(data.MethodName));

			var count = query.Count();
			var list = query
				.OrderByDescending(x=>x.ExecutionTime)
				.Skip((pageIndex - 1) * pageSize)
				.Limit(pageSize)
				.ToList();
				//.FindList(expression, pageIndex, pageSize).ToList();
			var result = new PageResult<AuditLog>();
			result.Total = count;
			result.Data = list;
			result.CurPageIndex = pageIndex;
			result.PageSize = pageSize;
			return await Task.FromResult(result);
		}

	}

	public class AuditLogPageQueryDto 
	{
        public string? MethodName { get; set; }
        public int PageIndex { get; set; }
        public int PageSize { get; set; }
    }

	public class PageResult<T>
	{
		public int Total { get; set; }
		public List<T> Data { get; set; }
        public int CurPageIndex { get; set; }
		public int PageSize { get; set; }
    }
}
